package cn.com.infcn.spider.domain;

import java.io.File;
import java.io.IOException;

import cn.com.infcn.spider.util.FtpConfiguration;
import cn.com.infcn.spider.util.FtpUtil;

import com.alibaba.fastjson.JSONObject;

public class FtpFile extends BinaryFile {
	
	private FtpConfiguration ftpConfig;
	
	private File localTemporaryFile;
	
	public FtpFile(FtpConfiguration ftpConfig, String path) {
		this.ftpConfig = ftpConfig;
		super.setFilePath(path);
		JSONObject obj = new JSONObject();
		obj.put("filePath", path);
		obj.put("fileName", this.getName());
		super.setResult(obj);
	}
	
	/**
	 * 下载到本地
	 */
	public String downloadToLocalTemporaryPath(){
		String path = getFilePath();
		FtpUtil ftpUtil = new FtpUtil(getFtpConfig());
		try {
			ftpUtil.connectServer();
			String infcn_path = System.getProperty("java.io.tmpdir") + File.separator + "infcn";
			File infcnPath = new File(infcn_path);
			if(!infcnPath.exists()){
				infcnPath.mkdirs();
			}
			String temPath = infcn_path + File.separator + getName();
			System.out.println(temPath);
			ftpUtil.downloadFile(path, temPath);
			localTemporaryFile = new File(temPath);
			return temPath;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		} finally{
			try {
				ftpUtil.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void cleanTemporaryFile(){
		if(localTemporaryFile != null){
			localTemporaryFile.delete();
			localTemporaryFile = null;
		}
	}
	
	public String getName(){
		String filename = getFilePath().substring(getFilePath().lastIndexOf("/") + 1);
		return filename;
	}
	
	public String getSuffix(){
		String suffix = getFilePath().substring(getFilePath().lastIndexOf(".")+1);
		return suffix;
	}

	public FtpConfiguration getFtpConfig() {
		return ftpConfig;
	}

	public File getLocalTemporaryFile() {
		return localTemporaryFile;
	}

}
